<?php

//This is the file called by cron to kick off the tgtai process for a single site

	
include_once (dirname(dirname(dirname(dirname(__FILE__)))) .  DIRECTORY_SEPARATOR."wp-load.php");
include_once('tgtai_process.php');
include_once('tgtai_classify.php');
include_once('tgtai_fcns.php');

global $blog_id, $wpdb;

//define global constants

define (MCT_AI_REDIR,'ailink');
define (MCT_AI_LOG_ERROR,'ERROR');
define (MCT_AI_LOG_ACTIVITY,'ACTIVITY');
define (MCT_AI_LOG_PROCESS,'PROCESS');

$proc_id = strval(rand(1,10000));
$proc_q = array();
$proc_q = get_option('mct_ai_proc_queue');
if (empty($proc_q)) {
    mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'Start Process: '.$proc_id.'  ', ' ');
} else {
        mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'Start Process: '.$proc_id.'  ', implode(',',$proc_q));
}
if (empty($proc_q)) {
    mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'Start Processing Site: '.$blog_id.'  ', '');
    //loop on blogs
     if (is_multisite()) {
        $sql = "SELECT `blog_id`
        FROM $wpdb->blogs";
        $blogs = $wpdb->get_results($sql, ARRAY_A);
     } else {
         $blogs[0]['blog_id]'] = 1;
     }
     foreach ($blogs as $thisblog){
        if (is_multisite()){
            if ($thisblog['blog_id'] != $blog_id){
                mct_ai_newblog($thisblog['blog_id']);
            }
            //Clean logs for this blog, postsread only if blog 1
            if ($blog_id == 1) mct_ai_clean_postsread(true);
            else mct_ai_clean_postsread(false);
        } else {
            mct_ai_clean_postsread(true);
        }
         //Build values - Loop on all train and active topics in this site
        $sql = "SELECT `topic_id`
                FROM $ai_topic_tbl
                WHERE topic_status != 'Inactive'";
        $topics = $wpdb->get_results($sql, ARRAY_A);
        if (empty($topics)){
            continue;
        }
        foreach ($topics as $topic){
            $proc_q[] = trim(strval($blog_id)).':'.trim(strval($topic['topic_id']));
        }
     }
     if (empty($proc_q)) exit();  //nothing to do
     if (is_multisite()) mct_ai_newblog(1);  //Options stay in blog 1
     update_option('mct_ai_proc_queue', $proc_q);  //set the option
     if (empty($proc_q)) {
         mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'End Process: '.$proc_id.'  ', ' ');
     } else {
         mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'End Process: '.$proc_id.'  ', implode(',',$proc_q));
     }
     mct_ai_new_proc();
     
     exit();
}
//pop q item and process it
$item = explode(':',array_pop($proc_q));
$thisblog = $item[0];
$thistopic = $item[1];
if (is_multisite()){
    mct_ai_newblog($thisblog);
}
//Get the topic
$sql = "SELECT *
    FROM $ai_topic_tbl
    WHERE topic_id = '$thistopic'";
    $topic = $wpdb->get_row($sql, ARRAY_A);
if (!empty($topic)){  //may have been deleted since we set up the queue
    if (!empty($topic['topic_last_run'])){
        $lastrun = strtotime($topic['topic_last_run']);
        $now = strtotime($wpdb->get_var('Select now()'));  //use mysql time
        if (($now - $lastrun) < 7200) {
            mct_ai_log($topic['topic_name'],MCT_AI_LOG_PROCESS, 'Stopping, Topic recently updated '.$proc_id.'  ', ' ');
            //delete_option('mct_ai_proc_queue');  //no more work
            exit();
        }
    }
    $sql = "UPDATE $ai_topic_tbl SET topic_last_run = now() WHERE topic_id = '$thistopic'";
    $wpdb->query($sql);
    mct_ai_process_topic($topic);
}
//All done, 
if (is_multisite()) mct_ai_newblog(1);  //Options stay in blog 1
if (empty($proc_q)){
    mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'End Process: '.$proc_id.'  ', ' ');
    mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'End Site Processing: '.$blog_id.'  ', '');
    delete_option('mct_ai_proc_queue');
} else {
    update_option('mct_ai_proc_queue',$proc_q);
    mct_ai_log('Blog',MCT_AI_LOG_PROCESS, 'End Process: '.$proc_id.'  ', implode(',',$proc_q));
    mct_ai_new_proc(); //Start the next process 
}
exit();


function mct_ai_new_proc(){
    $url = plugins_url().'/TargetAI/tgtai_process_page.php';
	
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);  //Set timeout to 1ms so we return and let it run

    curl_exec($ch);
    curl_close($ch);
}

function mct_ai_newblog($bid){
    //switches blog and sets globals
   global $wpdb, $ai_topic_tbl, $ai_postsread_tbl, $ai_sl_pages_tbl, $ai_logs_tbl, $mct_ai_optarray, $mct_sl_optarray;
   
   switch_to_blog($bid);
   //Set up tables, options for this blog
   $ai_topic_tbl = $wpdb->prefix.'topic';
   //$ai_postsread_tbl = 'postsread';  Only one master table, so don't change name
   $ai_sl_pages_tbl = $wpdb->prefix.'sl_pages';
   $ai_logs_tbl = $wpdb->prefix.'ai_logs';
   $mct_ai_optarray = get_option('mct_ai_options');
   // Get savelink options also as they hook onto post insert
   $mct_sl_optarray = get_option('mct_sl_options');
}
?>